//
//  DMControllerfour.m
//  DMGME
//
//  Created by ihope99 on 15/8/27.
//  Copyright (c) 2015年 GYP. All rights reserved.
//

#import "DMStoreInfoController.h"
#import "CollectionController.h"
#import "ServiceControllerView.h"
#import <BaiduMapAPI/BMKLocationService.h>
#import "mapVTool.h"
#import <BaiduMapAPI/BMKGeocodeSearchOption.h>
#import <BaiduMapAPI/BMKGeocodeSearch.h>
#import "PhotoSelectManager.h"
#import "AFHTTPRequestOperationManager.h"
#import "ShopTypeController.h"
#import "UIImageView+WebCache.h"




@interface DMStoreInfoController ()<BMKLocationServiceDelegate,BMKPoiSearchDelegate,BMKGeoCodeSearchDelegate,UIScrollViewDelegate,UIActionSheetDelegate>

@end

@implementation DMStoreInfoController
{
    BMKLocationService *locService;    // 定位
    BMKGeoCodeSearch* _geocodesearch;  // 地理位置检索
    BMKPoiSearch *_poiSearch;   // poi 检索
    PhotoSelectManager *mPhotoManager;
    NSString *mLocation;//店铺经纬度
    NSString *mAdressStr;//店铺地址
    NSString *mShopType; //店铺类型
    NSString *mCode; //上传的照片
    BOOL mCodeState; //上传图片状态
    UIImageView *upShouInfoImageView;
}
-(NSMutableDictionary *)dictAddress{
    if (_dictAddress == nil) {
        _dictAddress = [NSMutableDictionary dictionary];
    }
    return _dictAddress;
}
-(NSArray *)array{
    if (_array == nil) {
        _array = [NSArray array];
    }
    return _array;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"店铺信息";
    self.view.backgroundColor = [UIColor whiteColor];
    
    mCodeState = NO;

    
    _storeName.inputAccessoryView = [self GetInputAccessoryView];
    _storeAdress.inputAccessoryView = [self GetInputAccessoryView];
    _bossName.inputAccessoryView = [self GetInputAccessoryView];
    _phoneNum.inputAccessoryView = [self GetInputAccessoryView];
    
    _bossName.text = _mNamestr;
    _phoneNum.text = _mPhoneNumstr;
    
    
    [self AddLeftImageBtn:[UIImage imageNamed:@"fanhui_03 2"]target:self action:@selector(GoBack)];
    [_exchangeStoreInfoBtn addTarget:self action:@selector(_exchangeStoreInfoBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_upDownAdressPoiBtn addTarget:self action:@selector(comUpDownClick) forControlEvents:UIControlEventTouchUpInside];
    [_upShopInfo addTarget:self action:@selector(_upShopInfoBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_setShopType addTarget:self action:@selector(setShoptypeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    mPhotoManager = [[PhotoSelectManager alloc] init];
    mPhotoManager.delegate = self;
    mPhotoManager.mbEdit = NO;
    mPhotoManager.mRootCtrl = self;
    mPhotoManager.OnPhotoSelect = @selector(OnPhotoSelect:);
    //创建地图
    
    [self creatBMPView];
    if ([_exchangShopType isEqual:@"ex"]) {
        [self storeShopInfoNet];
    }
    
}

- (void)storeShopInfoNet{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue: [AFDownManager MD5String:@"%^&*dongmangoug!@#$getShop"] forKey:@"token"];
    [dict setValue: @"getShop" forKey:@"action"];
    [dict setValue: kkUserDict[@"id"] forKey:@"agent_id"];
    [AFDownManager POST:UpShopPitch parameters:dict success:^(id responseObject) {
//        NSLog(@"%@",responseObject);
        if ([responseObject[@"data"][@"shoptype"] isKindOfClass:[NSNull class]]) {
            return ;
        }
        
        _storeName.text = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"storename"]];
        _storeAdress.text = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"address"]] ;
        _bossName.text = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"realname"]];
        _phoneNum.text = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"phone"]];
        [_setShopType setTitle:responseObject[@"data"][@"shoptype"][@"title"] forState:UIControlStateNormal];
        mShopType = responseObject[@"data"][@"shoptype"][@"id"];
        [_setShopType setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        upShouInfoImageView = [[UIImageView alloc] init];
        upShouInfoImageView.frame = _upShopInfo.frame;
        [upShouInfoImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",responseObject[@"data"][@"cover"]]] placeholderImage:nil];
        [self.view addSubview:upShouInfoImageView];
        mCode = responseObject[@"data"][@"cover"];
        mCodeState = YES;
        mLocation = [NSString stringWithFormat:@"%@,%@",responseObject[@"data"][@"lng"],responseObject[@"data"][@"lat"]];
        [_upDownAdressPoiBtn setTitle:@"您已上传" forState:UIControlStateNormal];
        
        
        

//        _storeTypeLable.text = [NSString stringWithFormat:@"店铺类别:  %@",responseObject[@"data"][@"shoptype"][@"title"]];
//        _storecolatian.text =[NSString stringWithFormat:@"上传店铺封面: %@,%@",responseObject[@"data"][@"lat"],responseObject[@"data"][@"lng"]] ;
//        NSLog(@"%@",responseObject[@"data"][@"cover"]);
//        
//        [_storeImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",responseObject[@"data"][@"cover"]]] placeholderImage:nil];
    } failure:^(NSError *error) {
    }];
}



- (void)_upShopInfoBtnClick{
    UIActionSheet *actionView = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"返回" destructiveButtonTitle:@"照相" otherButtonTitles:@"从相册选择", nil];
    [actionView showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
        if (buttonIndex==0) {
            [mPhotoManager TakePhoto:YES];
            actionSheet.backgroundColor = [UIColor greenColor];
        }else if(buttonIndex==1){
            [mPhotoManager TakePhoto:NO];
        }
}
- (void)OnPhotoSelect:(PhotoSelectManager *)sender
{
    self.mLocalPath = sender.mLocalPath;
//    NSLog(@"local = %@",self.mLocalPath);
    [self upShopInfoNet];
}
#pragma mark - 创建百度地图
-(void)creatBMPView
{
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    //指定最小距离更新(米)，默认：kCLDistanceFilterNone
    [BMKLocationService setLocationDistanceFilter:100.f];
    
    //初始化BMKLocationService
    locService = [[BMKLocationService alloc]init];
    locService.delegate = self;
    
    //启动LocationService
    [locService startUserLocationService];
    
    [mapVTool sharedInstance].showsUserLocation = YES;
    [mapVTool sharedInstance].userTrackingMode = BMKUserTrackingModeNone;
    [mapVTool sharedInstance].zoomLevel = 18;
}

#pragma mark - 地图delegete事件
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
//    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
   
    [[mapVTool sharedInstance]updateLocationData:userLocation];
    [[mapVTool sharedInstance]setCenterCoordinate:userLocation.location.coordinate animated:NO];
    
    NSString *latitude = [NSString stringWithFormat:@"%f",userLocation.location.coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"%f", userLocation.location.coordinate.longitude];
    //
    [self.dictAddress setValue:latitude forKey:@"latitude"];
    [self.dictAddress setValue:longitude forKey:@"longitude"];
    //
    [mapVTool sharedInstance].addressDic = self.dictAddress;
    
    //    发起反向地理编码检索
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){[latitude floatValue],[longitude floatValue]};
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeoCodeSearchOption.reverseGeoPoint = pt;
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    _geocodesearch.delegate = self;
    
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeoCodeSearchOption];
    if(flag)
    {
//        NSLog(@"反geo检索发送成功");
    }
    else
    {
//        NSLog(@"反geo检索发送失败");
    }
}

//接收反向地理编码结果
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result
                        errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
//        NSLog(@"在此处理正常结果");
        
        //初始化检索对象
        _poiSearch =[[BMKPoiSearch alloc]init];
        _poiSearch.delegate = self;
        //发起检索
        BMKNearbySearchOption *option = [[BMKNearbySearchOption alloc]init];
        option.pageIndex = 1;
        option.pageCapacity = 20;
        option.radius = 500;
        option.location = CLLocationCoordinate2DMake([[self.dictAddress objectForKey:@"latitude"] floatValue],  [[self.dictAddress objectForKey:@"longitude"] floatValue]);
        
        [mapVTool sharedInstance].address = result.poiList;
    }
    else {
//        NSLog(@"抱歉，未找到结果");
    }
}
-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    locService.delegate = self;
    
    //启动LocationService定位
    [locService startUserLocationService];
    [mapVTool sharedInstance].showsUserLocation = YES;
    [mapVTool sharedInstance].userTrackingMode = BMKUserTrackingModeFollow;
    [mapVTool sharedInstance].zoomLevel = 18;
}

#pragma mark -
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    _poiSearch.delegate = nil;
    locService.delegate = nil;
    [locService stopUserLocationService];
}

#pragma mark - 店铺类别
- (void)setShoptypeBtnClick{
    ShopTypeController *shopType = [[ShopTypeController alloc] init];
    [shopType provinceStr:^(NSString *provinceStr, NSString *provinceId) {
//        NSLog(@"%@-%@",provinceId,provinceStr);
        mShopType = provinceId;
        [_setShopType setTitle:provinceStr forState:UIControlStateNormal];
    }];
    [self.navigationController pushViewController:shopType animated:YES];
}

- (void)upShopInfoNet{

    NSMutableDictionary *dict = [NSMutableDictionary dictionary];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager .responseSerializer =[AFJSONResponseSerializer serializer];

    [dict setValue: [AFDownManager MD5String:@"%^&*dongmangoug!@#$uploadCover"] forKey:@"token"];

    [dict setValue: @"uploadCover" forKey:@"action"];
    [dict setValue:_phoneNumstr forKey:@"mobile"];

    NSData *imageData = [NSData dataWithContentsOfFile:self.mLocalPath options:NSDataReadingMappedIfSafe error:nil];

    [manager POST:UpShopPitch parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        [formData appendPartWithFileData :imageData name:@"image" fileName:@"1.jpg" mimeType:@"image/jpeg"];

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"responseObject = %@",responseObject);
        if ([responseObject[@"code"] intValue] == 0) {
            
            [_upShopInfo setImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal];
            
            upShouInfoImageView.hidden = YES;
            mCode = responseObject[@"data"][@"cover"];
            mCodeState = YES;
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"error:%@",error);
    }];



}
#pragma mark - 上传店铺地图坐标
- (void)comUpDownClick{
    
    ServiceControllerView *serVv = [[ServiceControllerView alloc] init];
    [serVv adressPoiStr:^(NSString *adressLng, NSString *adressLat, NSString *adressStr) {
        mLocation = [NSString stringWithFormat:@"%@,%@",adressLng,adressLat];
        [_upDownAdressPoiBtn setTitle:@"您已上传" forState:UIControlStateNormal];
//        mAdressStr = adressStr;
    }];
    
    [self.navigationController pushViewController:serVv animated:YES];
}

#pragma mark - 修改店铺信息
- (void)_exchangeStoreInfoBtnClick
{
//    NSLog(@"%@",_exchangShopType);
    mAdressStr = _storeAdress.text;
    
    if (!_storeName.text||_storeName.text.length == 0) {
        [self showMsg:@"请输入店铺名字"];
    }else if (!_storeAdress.text||_storeAdress.text.length == 0){
        [self showMsg:@"请输入店铺地址"];
    }else if (!_bossName.text||_bossName.text.length == 0){
        [self showMsg:@"请输老板姓名"];
    }else if (!_phoneNum.text||_phoneNum.text.length == 0){
        [self showMsg:@"请输入手机号码"];
    }else if ([_setShopType.titleLabel.text isEqualToString:@"点击设置"]){
        [self showMsg:@"请设置店铺类别"];
    }else if (mCodeState == NO){
        [self showMsg:@"请上传店铺封面"];
    }else if ([_upDownAdressPoiBtn.titleLabel.text isEqualToString:@"点击上传"]){
        [self showMsg:@"请上传店铺坐标"];
    }else{
    
    if ([_exchangShopType isEqualToString:@"ex"]) {
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        
        [dict setValue: [AFDownManager MD5String:@"%^&*dongmangoug!@#$updateShop"] forKey:@"token"];
        [dict setValue: @"updateShop" forKey:@"action"];
        [dict setValue: _phoneNum.text forKey:@"phone"];
        [dict setValue: _phoneNumstr forKey:@"mobile"];
            [dict setValue: kkUserDict[@"id"] forKey:@"agent_id"];
        [dict setValue: mLocation forKey:@"location"];
        [dict setValue: mAdressStr forKey:@"address"];
//        NSLog(@"%@",mAdressStr);
        [dict setValue: _bossName.text forKey:@"realname"];
        [dict setValue: _storeName.text forKey:@"storename"];
                [dict setValue: kkUserDict[@"shop"][@"id"] forKey:@"id"];
//        NSLog(@"%@",kkUserDict);
        
        
        //        [dict setValue: kkUserDict[@"shop"][@"type"] forKey:@"type"];
                [dict setValue: mShopType forKey:@"type"];
        
        [dict setValue: mCode forKey:@"cover"];
        
//        NSLog(@"%@",dict);
        [AFDownManager POST:UpShopPitch parameters:dict success:^(id responseObject) {
//            NSLog(@"%@",responseObject);
//            NSLog(@"%@",responseObject[@"desc"]);
            
            if ([responseObject[@"code"] intValue] == 0) {
//                self.ShopId(responseObject[@"data"][@"id"]);
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [self showMsg:responseObject[@"desc"]];
            }
            
        } failure:^(NSError *error) {
        }];
        
    }else{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    [dict setValue: [AFDownManager MD5String:@"%^&*dongmangoug!@#$addShop"] forKey:@"token"];
    [dict setValue: @"addShop" forKey:@"action"];
    [dict setValue: _phoneNum.text forKey:@"phone"];
    [dict setValue: _phoneNumstr forKey:@"mobile"];
//    [dict setValue: kkUserDict[@"id"] forKey:@"agent_id"];
    [dict setValue: mLocation forKey:@"location"];
    [dict setValue: mAdressStr forKey:@"address"];
    [dict setValue: _bossName.text forKey:@"realname"];
    [dict setValue: _storeName.text forKey:@"storename"];
    
    [dict setValue: mShopType forKey:@"type"];
    [dict setValue: mCode forKey:@"cover"];
    
//    NSLog(@"%@",dict);
    [AFDownManager POST:UpShopPitch parameters:dict success:^(id responseObject) {
//        NSLog(@"%@",responseObject);
//        NSLog(@"%@",responseObject[@"desc"]);

        if ([responseObject[@"code"] intValue] == 0) {
            self.ShopId(responseObject[@"data"][@"id"]);
            [self.navigationController popViewControllerAnimated:YES];
           }
        else{
            [self showMsg:responseObject[@"desc"]];
        }
        
    } failure:^(NSError *error) {
    }];
    }
    }
}

- (void)ShopId:(void(^)(NSString *shopId))block{
    self.ShopId = block;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
